﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions ;
using System.Threading.Tasks;
using System.Web;

namespace SugarFineUI.Framework.Uitility
{
    /// <summary>
    /// http相关工具类
    /// </summary>
    public class HttpHelper
    {
        public static string GetRemotePage(string url)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = System.Net.WebRequest.Create(url) as HttpWebRequest;
                response = request.GetResponse() as HttpWebResponse;
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                return reader.ReadToEnd();
            }
            catch (WebException exception)
            {
                if (exception.Status == WebExceptionStatus.ProtocolError)
                {
                    response = (HttpWebResponse)exception.Response;
                }
                if (exception.Status == WebExceptionStatus.ConnectFailure)
                {
                    return exception.Message;
                }
            }
            catch (Exception)
            {
                if (response != null)
                {
                    response.Close();
                }
                return string.Empty;
            }
            if (response != null)
            {
                StreamReader reader2 = new StreamReader(response.GetResponseStream());
                string str = reader2.ReadToEnd();
                reader2.Close();
                response.Close();
                return str;
            }
            return string.Empty;
        }

        /// <summary>
        /// post提交,获取返回参数
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="value">参数(username=a&pwd=b)</param>
        /// <returns></returns>
        public static string PostRemotePage(string url, string value)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            try
            {
                request = (HttpWebRequest)System.Net.WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] bytes = Encoding.UTF8.GetBytes(value);
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException exception)
            {
                if (exception.Status == WebExceptionStatus.ProtocolError)
                {
                    response = (HttpWebResponse)exception.Response;
                }
                if (exception.Status == WebExceptionStatus.ConnectFailure)
                {
                    return exception.Message;
                }
            }
            catch (Exception)
            {
                if (response != null)
                {
                    response.Close();
                }
                return string.Empty;
            }
            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string str = reader.ReadToEnd();
                reader.Close();
                response.Close();
                return str;
            }
            return string.Empty;
        }

        #region URL参数加密解密

        /// <summary>
        /// Base64 转 string
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        private static string Base64ToString(string base64)
        {
            try
            {
                char[] charBuffer = base64.ToCharArray();
                byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
                return Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// string 转 base64
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string StringToBase64(string value)
        {
            try
            {
                byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(value);

                return Convert.ToBase64String(bytValue);
            }
            catch
            {
                return string.Empty;
            }
        }



        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Url64Encode(string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
            string s = StringToBase64(StringToBase64(value));

            return s.TrimEnd(new char[] { '=' });

        }

        public static string Url64Encode(int value)
        {
            return Url64Encode(value.ToString());
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Url64Decode(string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;

            string s = string.Empty;

            int nC = value.Length % 4;
            if (nC == 0)
            {
                s = value;
            }
            else
            {
                s = value + Repeat("=", 4 - nC);
            }
            return Base64ToString(Base64ToString(s));
        }
        /// <summary>
        /// 将字符串重复number次
        /// </summary>
        /// <param name="source"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        private static string Repeat(string source, int number)
        {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for (i = 0; i < number; i++) sb.Append(source);
            return sb.ToString();
        }
        #endregion

        /// <summary>
        /// 取得客户真实IP
        /// </summary>
        /// <returns></returns>
        public static string GetTrueUserIP()
        {
            string UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(UserIP))
                UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(UserIP))
                UserIP = HttpContext.Current.Request.UserHostAddress;
            if (UserIP == "::1")
                UserIP = "127.0.0.1";
            if (UserIP.IndexOf(".") == -1)//没有“.”肯定是非IPv4格式
                UserIP = "0.0.0.1";
            else
            {
                string temp = UserIP;
                UserIP = string.Empty;

                IPAddress ip;
                if (temp.IndexOf(",") != -1)
                {
                    //有“,”，估计多个代理。
                    temp = temp.Replace(" ", "").Replace("'", "");
                    string[] TempIPs = temp.Split(',');

                    StringBuilder sb = new StringBuilder();
                    foreach (var item in TempIPs)
                    {
                        if (IPAddress.TryParse(item, out ip))
                        {
                            sb.AppendFormat(",{0}", ip.ToString());
                            //UserIP += "," + ip.ToString();
                        }
                    }
                    if (sb.ToString().Length > 0)
                        UserIP = sb.ToString().Substring(1);
                }
                else
                {
                    if (IPAddress.TryParse(temp, out ip))
                    {
                        UserIP = ip.ToString();
                    }
                }

                if (UserIP.Length == 0)
                    UserIP = "0.0.0.2";
            }
            return UserIP;
        }

        /// <summary>
        /// 判断是否为手机端
        /// </summary>
        /// <returns></returns>
        public static bool IsMoblie()
        {
            string agent = (HttpContext.Current.Request.UserAgent + "").ToLower().Trim();

            if (agent == "" ||
                agent.IndexOf("mobile") != -1 ||
                agent.IndexOf("mobi") != -1 ||
                agent.IndexOf("nokia") != -1 ||
                agent.IndexOf("samsung") != -1 ||
                agent.IndexOf("sonyericsson") != -1 ||
                agent.IndexOf("mot") != -1 ||
                agent.IndexOf("blackberry") != -1 ||
                agent.IndexOf("lg") != -1 ||
                agent.IndexOf("htc") != -1 ||
                agent.IndexOf("j2me") != -1 ||
                agent.IndexOf("ucweb") != -1 ||
                agent.IndexOf("opera mini") != -1 ||
                agent.IndexOf("mobi") != -1 ||
                agent.IndexOf("android") != -1 ||
                agent.IndexOf("iphone") != -1)
            {
                //终端可能是手机
                return true;
            }

            return false;
        }

        /// <summary>
        /// 判断是否是微信客户端
        /// </summary>
        /// <returns></returns>
        public static bool IsWechat()
        {
            string param = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
            if (!string.IsNullOrEmpty(param) )
            {
                return param.ToLower().Contains("MicroMessenger".ToLower());
            }
            return false;
        }


        /// <summary>
        /// 判断是否是图片标签
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static bool IsImg(string Url)
        {
            return Regex.IsMatch(Url, @"(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$");
        }

      

    }
}
